<template>
  <div class="app-container file-data">
    <el-row class="header-form"/>
    <div class="table-list">
      <div class="file-data-title-row">
        <div class="title-flex">
          <Title :title="fileName ? `${fileName} ` : ''" :is-show="true" :total="total"/>
        </div>
        <div class="btn-right">
          <export-button :export-api="exportApi" :export-name="exportName"/>
        </div>
      </div>
      <el-row>
        <el-col v-if="tabs && tabs.length > 0" class="tabs-wrap">
          <el-tabs v-model="activeID" @tab-click="handleClick">
            <el-tab-pane v-for="tabItem in tabs" :key="tabItem.id" :label="tabItem.tabName" :name="tabItem.id + ''"/>
          </el-tabs>
        </el-col>
        <el-col v-loading="listLoading" class="data-wrap">
          <p v-if="list && list.length < 1" class="empty-text">暂无数据</p>
          <el-table
            v-else
            ref="dataTable"
            :data="list"
            :fit="true"
            :excess-rows="500"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="table-header-cell-nobottom"
            popper-class="aa"
            hightlight-current-row
            class="data-table"
            @cell-dblclick="onCellDBClick"
            @filter-change="filterChange">
            <el-table-column type="index" width="50"/>
            <!-- <el-table-column
              :label="firstTitle"
              width="100"
              align="left"
              show-overflow-tooltip
              resizable>
              <template slot-scope="scope">
                {{ scope.row[0] }}
              </template>
            </el-table-column> -->
            <el-table-column
              v-for="(titleItem, tIndex) in titles"
              :key="tIndex"
              :label="titleItem"
              :prop="titleItem"
              :column-key="tIndex === 0 ? '' : titleItem"
              :filter-multiple="false"
              :filters="titleList[tIndex] ? titleList[tIndex].items : []"
              :filter-method="filterHandler"
              min-width="100"
              align="left"
              show-overflow-tooltip
              resizable>
              <template slot-scope="scope">
                {{ scope.row[tIndex + 1] }}
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row type="flex" justify="end" class="pagination-area">
        <el-col :span="12" style="padding: 10px;">
          <el-button type="primary" size="small" @click="clearFilter">重置所有筛选条件</el-button>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-pagination
            v-show="list.length > 0"
            :current-page="params.page"
            :page-size="params.perPage"
            :total="total"
            layout="total, prev, pager, next, jumper"
            @current-change="handleCurrentChange" />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { getFileTabs, getFileData, getFileTitleList } from '@/api/brand';
import ExportButton from '@/components/ExportButton';
import Title from '@/components/Title';
import axios from 'axios';
export default {
  components: {
    ExportButton,
    Title
  },
  data() {
    return {
      list: [],
      firstTitle: '', // 单独获取第一个表头
      titles: [], // 去除表头的第一个 剩余的表头
      tabs: [],
      fileId: 0,
      fileName: '',
      activeID: '',
      listLoading: true,
      cacheData: {},
      listArr: [], // 获取筛选的值数组
      params: {
        page: 1,
        perPage: 250,
        list: ''
      },
      total: 0,
      titleList: [], // 获取表头的筛选数组
      cancelTitleHttp: null,
      cancelListHttp: null
    };
  },
  computed: {
    exportApi() {
      return `/admin/brand/file/${this.fileId}/data/export`;
    },
    exportName() {
      return this.fileName;
    }
  },
  created() {
    this.initData();
  },
  beforeDestroy() {
    this.cacheData = {};
  },
  methods: {
    handleClick(tab, event) {
      this.listLoading = true;
      this.cancelRequest(); // 取消请求
      if (this.list.length) { // 清除过滤
        this.$refs.dataTable.clearFilter();
      }
      this.resetData(); // 重置数据重新获取数据
    },
    getTabs() {
      return getFileTabs(this.fileId).then(({ data }) => {
        this.tabs = data;
        const id = data.length ? data[0].id : ''; // 用于预防接口没有返回数据
        this.activeID = id + '';
        return this.activeID;
      }, result => {
        return Promise.reject();
      });
    },
    getDataList(tabId, loadingShow, { page = 1, perPage, list }) {
      if (loadingShow) this.listLoading = true;

      const source = axios.CancelToken.source();
      getFileData(this.fileId, { tabId, page, perPage, list }, source.token).then(({ data }) => {
        this.list = data.items;
        this.titles = data.titles.slice(1);
        this.firstTitle = data.titles.shift();
        this.cacheData[tabId + ''] = data;
        this.params.page = data.page;
        this.params.perPage = data.perPage;
        this.total = data.total;
        this.listLoading = false;
      }, result => {
      }).catch(e => {
        this.listLoading = false;
        console.error(e);
      });
      this.cancelListHttp = source;
    },
    getTitleList(fileId, tabId) { // 获取表头筛选的数组
      const source = axios.CancelToken.source();
      getFileTitleList(fileId, tabId, source.token).then(res => {
        const data = res.data;
        data.forEach(item => { // 将获取的数组形式进行转化成element组件所需要的格式
          if (item.items.length) {
            item.items = item.items.map((val, i) => {
              const obj = {
                id: item.id,
                text: val,
                value: val
              };
              return obj;
            });
          }
        });
        this.titleList = data;
      }, result => {
      }).catch(e => {
        console.error(e);
      });
      this.cancelTitleHttp = source;
    },
    cancelRequest() {
      if (this.cancelTitleHttp) {
        this.cancelTitleHttp.cancel();
      }
      if (this.cancelListHttp) {
        this.cancelListHttp.cancel();
      }
    },
    initData() {
      this.fileId = Number(this.$route.params.fileId) || 0;
      const name = this.$route.query.name;
      this.fileName = name ? decodeURIComponent(name) : '';
      this.getTabs().then((tabID) => {
        this.getDataList(tabID, true, this.params);
        this.getTitleList(this.fileId, tabID); // 获取表头筛选列表
      });
    },
    onCellDBClick(row, column, cell, event) {
      this.$copyText(cell.innerText).then(e => {
        this.$message({
          message: '单元格复制成功',
          type: 'success'
        });
      }, (e) => {
        console.error(e);
      });
    },
    filterChange(filters) { // 获取表头筛选的list值
      let content;
      const list = {};
      let key;
      for (key in filters) { // 获取筛选的值
        content = filters[key][0]; // 获取相应key的值
        if (this.listArr.length) { // 当筛选条件有多个时
          const copyArr = this.listArr.map((ele, i) => {
            return ele.key === key && !content ? null : ele; // 判断已选择的筛选表头是否用户有选择了全部，如果选择全部则不push
          }).filter(i => !!i); // 删除掉
          copyArr.push({
            key: key,
            content: content
          });
          this.listArr = copyArr;
        } else { // 初始push进去筛选条件
          this.listArr.push({
            key: key,
            content: content
          });
        }
      }
      this.listArr.forEach(item => {
        if (this.titleList.length) {
          this.titleList.forEach(val => {
            if (val.items.length) {
              const isExist = val.items.find(ele => { // 获取筛选的值与表头数组是否相等
                return ele.value === item.content;
              });
              if (isExist) {
                list[isExist.id] = isExist.value; // 将id和值拼接
              }
            }
          });
        }
      });
      this.params.list = JSON.stringify(list) || '';
      this.params.page = 1;
      this.getDataList(Number(this.activeID), true, this.params);
      this.isFilter = true;
    },
    filterHandler(value, row, column) {
      return row.indexOf(value) !== -1;
    },
    clearFilter() { // 清除筛选数据
      if (this.list.length) {
        this.$refs.dataTable.clearFilter();
      }
      this.resetData(); // 重置数据
    },
    resetData() {
      this.listArr = [];
      // this.titleList = [];
      // this.list.splice(10, this.list.length);
      this.params.list = '';
      this.page = 1;
      setTimeout(() => {
        this.getDataList(Number(this.activeID), true, this.params);
        this.getTitleList(this.fileId, Number(this.activeID));
      }, 0);
    },
    handleCurrentChange(toPage) {
      this.params.page = toPage;
      this.getDataList(Number(this.activeID), true, this.params);
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss">
  .file-data {
    margin: 32px;
    box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
    border-radius:12px;
    background-color: #fff;
    padding: 32px 30px 10px 30px;
    .table-list {
      border-radius: 10px;
      .file-data-title-row {
        display: flex;
        align-items: center;
        margin-bottom: 40px;
        .title-flex {
          flex: 1;
        }
      }
      .el-row {
        padding: 0;
        .el-table {
          font-size: 14px;
          border:1px solid rgba(235,238,253,1);
          border-radius:0px 12px 12px 12px;
          &::before{
            display: none;
          }
        }
      }
      .tabs-wrap {
        background: white;
        & ::v-deep {
          .el-tabs__header {
            margin-bottom: 0;
            border-bottom: none;
          }
          .el-tabs__nav-wrap::after {
            display: none
          }
          .el-tabs__active-bar {
            display: none;
          }
          .el-tabs__item {
            // border-radius:0px 12px 0px 0px;
            padding: 0 34px;
            border:1px solid rgba(235,238,253,1);
            border-right: none;
            font-size:16px;
            border-radius:0;
            font-family:PingFangSC-Medium,PingFang SC;
            &:nth-child(2) {
              border-top-left-radius: 12px;
            }
            &:last-child {
              border-top-right-radius: 12px;
              border-right:1px solid rgba(235,238,253,1);
            }
            &.is-active {
              color: #fff;
              background:linear-gradient(142deg,rgba(116,167,255,1) 0%,rgba(64,110,255,1) 100%);
            }
          }
        }
      }
      .data-wrap {
        background: white;
        border-radius: 10px;
        min-height: 100px;
        .empty-text {
          text-align: center;
          margin-top: 45px;
        }
      }
    }
    .el-row {
      padding: 0 20px 0 0;
      .el-col-8.btn-right {
        display: flex;
        justify-content: flex-end;
        align-items: center;
      }
    }
    .el-table-filter { // 设置筛选下拉框的滚动条
      max-height: 500px;
      overflow-y: scroll;
    }
  }
  ul.el-table-filter__list { // 设置筛选下拉框的滚动条
    max-height: 400px;
    overflow-y: scroll;
  }
  .data-table {
    .el-table__column-filter-trigger i { // 设置筛选下箭头颜色
      color: #888 !important;
    }
  }
</style>
